import Cookies from 'js-cookie'
import dateFunc from '@/utils/dateFunc'
import axios from 'axios';
import URLCONSTANT from './constant/src/urlConstants'


/**
字符串
身份证
手机号
rootUrl
token
deepclone
**/

export default class commonUtils {
    /**
     * 判断字符串是否为空
     * @param str
     * @returns {boolean}
     */
    static isNull(str) {
        return str == null || str.length === 0 || str === '';
    }

    /**
     *
     * @desc  判断是否为身份证号
     * @param  {String|Number} str
     * @return {Boolean}
     */
    static isIdCard(str) {
        return /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(str)
    }

    /**
     *
     * @desc   判断是否为手机号
     * @param  {String|Number} str
     * @return {Boolean}
     */
    static isPhoneNum(str) {
        return /^(0|86|17951)?(1[3-9][0-9])[0-9]{8}$/.test(str)
    }

    static getRootURL() {
        var pathName = window.location.pathname.substring(1);
        var webName = pathName == '' ? '' : pathName.substring(0, pathName.indexOf('/'));
        if (webName == "") {
            return window.location.protocol + '//' + window.location.host;
        } else {
            return window.location.protocol + '//' + window.location.host + '/' + webName;
        }
    }

    static getIpAndPort(){
        return window.location.protocol + '//' + window.location.host;
    }


}

let C_objectIdSeq = 1001;

export function getInstId() {
    return dateFunc.format(new Date(), 'YYYYMMDDhhmmss') + Math.round(Math.random() * 10000) + C_objectIdSeq++
}

export function getNppmServiceToken() {
    var token = getToken();
    if(process.env.NODE_ENV === 'development'){
        token='eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJzdGFmZkNvZGVcIjpcIlBQTTEwMDFcIixcIm9yZ0lkXCI6MTAwLFwib3JnTmFtZVwiOlwi5Lit5Zu955S15L-h6ZuG5Zui5YWs5Y-4XCIsXCJzdGFmZklkXCI6MTAwMSxcInN5c3RlbVVzZXJJZFwiOjEwMDEsXCJzdGFmZk5hbWVcIjpcIlBQTeezu-e7n-euoeeQhuWRmFwiLFwiYmluZE51bWJlclwiOlwiMTg2NDk3MTMzMzhcIixcInJlZ2lvbklkXCI6MTAwMDA4MTAwMDAwLFwicmVnaW9uTmFtZVwiOlwi5Lit5Zu9XCIsXCJjaGFubmVsSWRcIjpcIlwiLFwiY2hhbm5lbE5hbWVcIjpcIlwiLFwiaXNTdXBlck1hbmFnZXJcIjp0cnVlLFwibG9naW5lZERhdGVcIjpcIjIwMTkwOTA2MDk1MjU0XCJ9IiwicHdkIjoiSSdtIHBhc3N3b3JkIiwiaWF0IjoxNTY3NzM0Nzc0LCJleHAiOjE1Njc4MjExNzR9.ddnNN6Ik5LBlIue5MwnThDxhIlrkN9gMkH-r9HNgtzs';
    }
    return token;
}

export function getToken() {
    return Cookies.get("token");
}

export function setToken(token) {
    return Cookies.set("token", token)
}

export function removeToken() {
    return Cookies.remove("token")
}

export function getCookie(name){
    return Cookies.get(name)
}
export function setCookie(name,value){
    return  Cookies.set(name, value)
}


const expireCookie = function (token) {
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
        Cookies.remove(cookies[i].split("=")[0])
    }
    window.location.href = '../login';
}

const SYS_DATA_TPL = new Map();
export function getSysDataByCode(sysCodes,busiTemplateId,callback,errCallBack){
    //查询是异步的,返回时可能没有值,所以用回调函数或者promise
    var that = this;
    var ret = {};

    var reQueryCodes = '';
    for(var key in sysCodes){
        var code = sysCodes[key]
        ret[code] = SYS_DATA_TPL.get(busiTemplateId+'_'+code);
        if(!ret[sysCodes[key]]){
            reQueryCodes += code+',';
        }
    }

    if(reQueryCodes.lastIndexOf(',') == reQueryCodes.length-1){
        reQueryCodes = reQueryCodes.substr(0, reQueryCodes.length - 1);
    }
    if(reQueryCodes){
        const url = URLCONSTANT.API_MUL_DICTIONARIES;
        var param = {
            sysDataCodes: reQueryCodes,
            busiTemplateId:busiTemplateId
        }
        axios.post(url,param)
        .then(function (response) {
            var json = JSON.parse(response.data);
            for(var key in json.info.data){
                var item = json.info.data[key];
                for(var j in item){
                    Object.assign(item[j],{
                        label:item[j].valueName,
                        value:item[j].valueCode,
                    })
                }
                SYS_DATA_TPL.set(busiTemplateId+'_'+key,item);
            }
            if(!!callback ){
                  for(var key in sysCodes){
                        var code = sysCodes[key]
                        ret[code] = SYS_DATA_TPL.get(busiTemplateId+'_'+code);
                   }

                  callback(ret);
            }
        })
        .catch(function (error) {
             console.log('[ppm err]: 取主数据失败,重试');
             console.log(sysCodes)
             console.log(error);
             if(!!errCallBack){
                 errCallBack(error);
             }
        });
    }else{
         if(!!callback){
             callback(ret);
        }
    } 
}
export function cleanBlankParamKey(param){
    var newParam = {};
    for(var key in param){
        if(param[key] && param[key] != '' && param[key] != null){
            newParam[key] = param[key];
        }
    }
    return newParam;
}
const Base64 = function () {
    // private property
    const _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
    // private method for UTF-8 encoding
    const _utf8_encode = function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    }

    // private method for UTF-8 decoding
    const _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = 0;
        var c1 = 0;
        var c2 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                var c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
    // public method for encoding
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = _utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    }

    // public method for decoding
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/_/g,'/');
        input = input.replace(/-/g,'+');
        input = input.replace(/[^A-Za-z0-9\+\/\=\-\_]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    }

  
}


export function getStaffInfo() {
    const staffInfo = Cookies.get("staffInfo") ;

    if (!staffInfo) {
        // alert('登录过期，请重新登录?', '提示', function() {
        //     expireCookie();
        // });
        return {};
    }else{
        var base = new Base64();
        return JSON.parse( base.decode(staffInfo));
    }
}



export function deepCloneObj(obj) {
    if (typeof(obj) == 'undefined') {
        return obj;
    }
    var str, newobj = obj.constructor === Array ? [] : {};
    if (typeof obj !== 'object') {
        return;
    } else if (window.JSON) {
        str = JSON.stringify(obj), //系列化对象
            newobj = JSON.parse(str); //还原
    } else {
        for (var i in obj) {
            newobj[i] = typeof obj[i] === 'object' ?
                deepCloneObj(obj[i]) : obj[i];
        }
    }
    return newobj;
};

export  function isEmpty(value) {
    return (Array.isArray(value) && value.length === 0)
        || (Object.prototype.isPrototypeOf(value) && Object.keys(value).length === 0);
};

export function debounce(func, wait, immediate) {
    let timeout, args, context, timestamp, result

    const later = function() {
        // 据上一次触发时间间隔
        const last = +new Date() - timestamp

        // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
            // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
            if (!immediate) {
                result = func.apply(context, args)
                if (!timeout) context = args = null
            }
        }
    }

    return function(...args) {
        context = this
        timestamp = +new Date()
        const callNow = immediate && !timeout
        // 如果延时不存在，重新设定延时
        if (!timeout) timeout = setTimeout(later, wait)
        if (callNow) {
            result = func.apply(context, args)
            context = args = null
        }

        return result
    }
}
